import mongoose from 'mongoose';
import joigoose from 'joigoose';

import * as validation from '../validation';
import { LIMITERS } from '../constants';

const Joigoose = joigoose(mongoose);

export default Object.entries(validation).reduce((obj, [field, schema]) => {
	if (field === 'balance') {
		const s = (obj[field] = new mongoose.Schema(Joigoose.convert(schema), {
			toObject: { virtuals: true },
			toJSON: { virtuals: true },
		}));
		Object.keys(LIMITERS).forEach(key => {
			s.virtual(`balance.${key}.value`).get(function () {
				const { total, used = 0 } = this[key] || this.balance[key];
				return total - used;
			});
		});
	} else {
		obj[field] = new mongoose.Schema(Joigoose.convert(schema));
	}

	return obj;
}, {});
